/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.condition;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

/**使用String数组表示，数组中每个元素代表请求参数匹配表达式，可以实现参数值匹配、参数存在匹配、参数值不匹配、参数不存在匹配4种不同的条件
 * <br/>其内部保存请求参数条件数组，对应于@RequestMapping的params数组属性，类型是ParamExpression，用于封装params属性数组中的值为参数表达式。
 * <br/>A logical conjunction (' && ') request condition that matches a request against
 * a set parameter expressions with syntax defined in {@link RequestMapping#params()}.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public final class ParamsRequestCondition extends AbstractRequestCondition<ParamsRequestCondition> {

	/**保存请求参数表达式集合
	 */
	private final Set<ParamExpression> expressions;


	/**构造方法，传入参数为参数表达式字符串数组
	 * <br/>Create a new instance from the given param expressions.
	 * @param params expressions with syntax defined in {@link RequestMapping#params()}; if 0, the condition will match to every request.
	 */
	public ParamsRequestCondition(String... params) {
		// 通过方法parseExpressions解析string类型的params条件数组为ParamExpression集合并构造
		this(parseExpressions(params));
	}

	/**通过list构造对象，主要目的是把传入的数组转换为set存储
	 * @param conditions
	 */
	private ParamsRequestCondition(Collection<ParamExpression> conditions) {
		this.expressions = Collections.unmodifiableSet(new LinkedHashSet<ParamExpression>(conditions));
	}


	/**解析参数表达式字符串数组为ParamExpression实例集合
	 * @param params
	 * @return
	 */
	private static Collection<ParamExpression> parseExpressions(String... params) {
		Set<ParamExpression> expressions = new LinkedHashSet<ParamExpression>();
		if (params != null) {
			for (String param : params) {
				expressions.add(new ParamExpression(param));
			}
		}
		return expressions;
	}


	/**
	 * Return the contained request parameter expressions.
	 */
	public Set<NameValueExpression<String>> getExpressions() {
		return new LinkedHashSet<NameValueExpression<String>>(this.expressions);
	}

	@Override
	protected Collection<ParamExpression> getContent() {
		return this.expressions;
	}

	@Override
	protected String getToStringInfix() {
		// 可以看到在匹配时，该条件需要满足所有的表达式匹配才可以返回结果，因此，返回的结果只需要是自己的实例，即可代表全部匹配结果
		// 基于这个逻辑，多个参数表达式之间为“与”的关系，其getToStringInfix方法返回“与”的关系
		return " && ";
	}

	/**
	 * Returns a new instance with the union of the param expressions
	 * from "this" and the "other" instance.
	 */
	@Override
	public ParamsRequestCondition combine(ParamsRequestCondition other) {
		// 直接对两个参数条件的参数表达式集合进行合并
		Set<ParamExpression> set = new LinkedHashSet<ParamExpression>(this.expressions);
		set.addAll(other.expressions);
		return new ParamsRequestCondition(set);
	}

	/**
	 * Returns "this" instance if the request matches all param expressions;
	 * or {@code null} otherwise.
	 */
	@Override
	public ParamsRequestCondition getMatchingCondition(HttpServletRequest request) {
		for (ParamExpression expression : expressions) {
			// 有一个表达式匹配结果为false，就视为整个条件不匹配，匹配逻辑封装在参数表达式中
			if (!expression.match(request)) {
				return null;
			}
		}
		// 只有在全部表达式匹配结果都为true或表达式列表为空时，才返回当前实例作为匹配结果
		return this;
	}

	/**在对多个匹配结果进行排序时，基于匹配条件越明确则匹配结果越好的规则，必然是匹配上的参数表达式越多，匹配结果越好。那么其实现逻辑就应该是直接判断参数表达式集合的大小
	 * <br/>Returns:
	 * <ul>
	 * <li>0 if the two conditions have the same number of parameter expressions
	 * <li>Less than 0 if "this" instance has more parameter expressions
	 * <li>Greater than 0 if the "other" instance has more parameter expressions
	 * </ul>
	 * <p>It is assumed that both instances have been obtained via
	 * {@link #getMatchingCondition(HttpServletRequest)} and each instance
	 * contains the matching parameter expressions only or is otherwise empty.
	 */
	@Override
	public int compareTo(ParamsRequestCondition other, HttpServletRequest request) {
		return (other.expressions.size() - this.expressions.size());
	}


	/**
	 * Parses and matches a single param expression to a request.
	 */
	static class ParamExpression extends AbstractNameValueExpression<String> {

		ParamExpression(String expression) {
			super(expression);
		}

		@Override
		protected boolean isCaseSensitiveName() {
			return true;
		}

		@Override
		protected String parseValue(String valueExpression) {
			return valueExpression;
		}

		@Override
		protected boolean matchName(HttpServletRequest request) {
			return WebUtils.hasSubmitParameter(request, this.name);
		}

		@Override
		protected boolean matchValue(HttpServletRequest request) {
			return ObjectUtils.nullSafeEquals(this.value, request.getParameter(this.name));
		}
	}

}
